package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.StudySystemException;
import com.xuecheng.learning.config.PayNotifyConfig;
import com.xuecheng.learning.service.MyCourseTableService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 接收消息通知
 * @author Tang
 * @version 1.0
 * @date 2024/1/25 16:32
 */
@Service
@Slf4j
public class ReceivePayNotifyService {
    /** 购买课程 **/
    private final static String PURCHASE_COURSE = "60201";
    @Autowired
    MyCourseTableService myCourseTableService;
    @RabbitListener(queues = PayNotifyConfig.PAYNOTIFY_QUEUE)
    public void receive(Message message) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.error(e.getLocalizedMessage());
        }
        String jsonString = new String(message.getBody());
        // 转成对象
        MqMessage mqMessage = JSON.parseObject(jsonString, MqMessage.class);
        // 根据消息内容更新选课记录表，先课程表写入
        String orderType = mqMessage.getBusinessKey2();
        if (PURCHASE_COURSE.equals(orderType)) {
            boolean success = myCourseTableService.saveChooseCourseSuccess(mqMessage.getBusinessKey1());
            if (!success) {
                StudySystemException.cast("保存选课记录状态失败");
            }
        }
    }
}
